<template>
    <div class="koi-flex">
        <KoiCard>
            <!-- 搜索条件 -->
            <el-form @submit.native.prevent v-show="showSearch" :inline="true">
                <el-form-item label="用户名称" prop="username">
                    <el-input placeholder="请输入用户名称" v-model="searchParams.nickname" clearable style="width: 200px"
                        @keyup.enter.native="handleListPage"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="search" plain v-debounce="handleSearch">搜索</el-button>
                    <el-button type="danger" icon="refresh" plain v-throttle="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>

            <!-- 表格头部按钮 -->
            <el-row :gutter="10">
                <el-col :span="1.5" v-auth="['system:role:add']">
                    <el-button type="primary" icon="plus" plain @click="handleAdd()">新增</el-button>
                </el-col>
                <el-col :span="1.5" v-auth="['system:role:delete']">
                    <el-button type="danger" icon="delete" plain @click="handleBatchDelete()"
                        :disabled="multiple">删除</el-button>
                </el-col>
                <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleListPage"></KoiToolbar>
            </el-row>

            <div class="h-20px"></div>
            <el-table v-loading="loading" border empty-text="暂时没有数据哟🌻" :data="tableList"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="序号" prop="id" width="80px" align="center" type="index"></el-table-column>
                <el-table-column label="登录账号" prop="username" align="center"
                    :show-overflow-tooltip="true"></el-table-column>
                <el-table-column label="头像" prop="avatar" width="80px" align="center">
                    <template #default="scope">
                        <div class="flex flex-justify-center">
                            <el-image class="rounded-full w-36px h-36px" :preview-teleported="true" fit="cover"
                                :preview-src-list="[scope.row.avatar]" :src="scope.row.avatar != null && scope.row.avatar != ''
                                        ? scope.row.avatar
                                        : 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
                                    ">
                                <template #error>
                                    <el-icon class="text-[--el-color-primary]" :size="36">
                                        <CircleCloseFilled />
                                    </el-icon>
                                </template>
                            </el-image>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="用户名称" prop="nickname" width="120px" align="center"
                    :show-overflow-tooltip="true"></el-table-column>
                <el-table-column label="邮箱" prop="email" width="220px" align="center"
                    :show-overflow-tooltip="true"></el-table-column>
                <!-- 注意：如果后端数据返回的是字符串"0" OR "1"，这里的active-value AND inactive-value不需要加冒号，会认为是字符串，否则：后端返回是0 AND 1数字，则需要添加冒号 -->
                <el-table-column label="用户状态" prop="status" width="100px" align="center">
                    <template #default="scope">
                        <el-switch :model-value="scope.row.status" active-text="启用" inactive-text="停用" :active-value="1"
                            :inactive-value="0" :inline-prompt="true" @change="handleSwitch(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作时间" prop="updateTime" width="180px" align="center"></el-table-column>
                <el-table-column label="操作" align="center" width="150" fixed="right"
                    v-auth="['system:role:update', 'system:role:delete']">
                    <template #default="{ row }">
                        <el-tooltip content="修改🌻" placement="top">
                            <el-button type="primary" icon="Edit" circle plain @click="handleUpdate(row)"
                                v-auth="['system:role:update']"></el-button>
                        </el-tooltip>
                        <el-tooltip content="删除🌻" placement="top">
                            <el-button type="danger" icon="Delete" circle plain @click="handleDelete(row)"
                                v-auth="['system:role:delete']"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <div class="h-20px"></div>
            <!-- 分页 -->
            <el-pagination background v-model:current-page="searchParams.page" v-model:page-size="searchParams.pageSize"
                v-show="total > 0" :page-sizes="[5, 10, 20 , 30 ,50]" layout="total, sizes, prev, pager, next, jumper"
                :total="total" @size-change="handleListPage" @current-change="handleListPage" />

            <!-- 添加 OR 修改 -->
            <KoiDrawer ref="koiDrawerRef" :title="title" :closeMethod="closeMethod" @koiConfirm="handleConfirm"
                @koiCancel="handleCancel" :loading="confirmLoading">
                <template #content>
                    <el-form ref="formRef" :rules="rules" :model="form" label-width="80px" status-icon>
                        <el-row>
                            <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                                <el-form-item label="登录账号" prop="username">
                                    <el-input v-model="form.username" placeholder="请输入用户名称" clearable
                                        :disabled="needPwd ? false :true" />
                                </el-form-item>
                            </el-col>
                            <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                                <el-form-item label="用户名称" prop="nickname">
                                    <el-input v-model="form.nickname" placeholder="请输入用户名称" clearable />
                                </el-form-item>
                            </el-col>
                            <el-col v-if="needPwd" :sm="{ span: 24 }" :xs="{ span: 24 }">
                                <el-form-item label="登录密码" prop="password">
                                    <el-input v-model="form.password" placeholder="密码默认123456(不输入密码)" clearable />
                                </el-form-item>
                            </el-col>
                            <el-col v-if="needStatus" :sm="{ span: 24 }" :xs="{ span: 24 }">
                                <el-form-item label="用户状态" prop="status">
                                    <el-select v-model="form.status" placeholder="请选择用户状态" clearable>
                                        <el-option label="启用" :value="1" />
                                        <el-option label="停用" :value="0" />
                                        <!-- <el-option v-for="item in userTypeOptions" :label="item.key" :value="item.value" /> -->
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                                <el-form-item label="邮箱" prop="email">
                                    <el-input v-model="form.email" type="email" placeholder="请输入邮箱"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                                <el-form-item label="用户头像" prop="avatar">
                                    <KoiUploadImage v-model:imageUrl="form.avatar" :fileSize="5">
                                        <template #content>
                                            <el-icon>
                                                <Avatar />
                                            </el-icon>
                                            <span>请上传头像</span>
                                        </template>
                                        <template #tip>图片最大为 5M</template>
                                    </KoiUploadImage>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </template>
            </KoiDrawer>
        </KoiCard>
    </div>
</template>

<script setup lang="ts" name="userPage">
// 已使用字典案例
import { nextTick, ref, reactive, onMounted } from "vue";
// @ts-ignore
import {
    koiMsgSuccess,
    koiNoticeSuccess,
    koiNoticeError,
    koiMsgError,
    koiMsgWarning,
    koiMsgBox,
    koiMsgInfo
} from "@/utils/koi.ts";
// @ts-ignore
import { listPage, getById, add, update, deleteById, batchDelete, updateStatus } from "@/api/system/user/index.ts";
// @ts-ignore
import { listDataByType } from "@/api/system/dict/data/index.ts";

import { getUserList, changeStatus, getUserInfoById, changeUserInfo, addUserInfo, deleteUser } from "@/api/system/user/index"

// 表格加载动画Loading
const loading = ref(false);
// 是否显示搜索表单[默认显示]
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 表格数据
const tableList = ref<any>([]);
// 需要输入密码
const needPwd = ref(false)
// 需要status
const needStatus = ref(false)

// 查询参数
const searchParams = ref({
    page: 1, // 第几页
    pageSize: 10, // 每页显示多少条
    nickname: "",
    username: "",
});

const total = ref<number>(0);

/** 重置搜索参数 */
const resetSearchParams = () => {
    searchParams.value = {
        page: 1,
        pageSize: 10,
        nickname: "",
        username: "",
    };
    dateRange.value = [];
};

/** 搜索 */
const handleSearch = () => {
    console.log("搜索");
    searchParams.value.page = 1;
    handleListPage();
};

/** 重置 */
const resetSearch = () => {
    console.log("重置搜索");
    resetSearchParams();
    handleListPage();
};

// 时间
const dateRange = ref();

/** @current-change：点击分页组件页码发生变化：例如：切换第2、3页 OR 上一页 AND 下一页 OR 跳转某一页 */
/** @size-change：点击分页组件下拉选择条数发生变化：例如：选择10条/页、20条/页等 */
// 分页查询，@current-change AND @size-change都会触发分页，调用后端分页接口
/** 数据表格 */
const handleListPage = async () => {
    try {
        loading.value = true
        let res = await getUserList(searchParams.value)
        tableList.value = res.data.records;
        total.value = res.data.total;
        loading.value = false;
    } catch { 
        koiMsgError("获取失败")
    }
};

onMounted(() => {
    // 获取表格数据
    handleListPage();
    handleDict();

});

// 翻译数据[用户类型]
const userTypeOptions = ref();

/** 字典翻译 */
const handleDict = async () => {
    try {
        userTypeOptions.value = [

        ];
        const res: any = await listDataByType("sys_status");
        console.log("字典数据", res.data);
        userTypeOptions.value = res.data;
    } catch (error) {
        console.log(error);
        koiMsgError("数据字典查询失败，请刷新重试🌻");
    }
};

const ids = ref([]); // 选择数组
const single = ref<boolean>(true); // 非单个禁用
const multiple = ref<boolean>(true); // 非多个禁用

/** 是否多选 */
const handleSelectionChange = (selection: any) => {
    // console.log(selection);
    ids.value = selection.map((item: any) => item.id);
    single.value = selection.length != 1; // 单选
    multiple.value = !selection.length; // 多选
};

/** 添加 */
const handleAdd = () => {
    // 打开对话框
    koiDrawerRef.value.koiOpen();
    koiMsgSuccess("添加🌻");
    // 重置表单
    resetForm();
    // 标题
    title.value = "用户添加";
    form.value.status = 1;
    needPwd.value = true
};

/** 回显数据 */
const handleEcho = async (id: any) => {
    if (id == null || id == "") {
        koiMsgWarning("请选择需要修改的数据🌻");
        return;
    }
    try {
        const res: any = await getUserInfoById(id);
        form.value = res.data;
 
    } catch (error) {
        koiNoticeError("数据获取失败，请刷新重试🌻");
        console.log(error);
    }
};

/** 修改 */
const handleUpdate = async (row?: any) => {
    // 打开对话框
    koiDrawerRef.value.koiOpen();
    needStatus.value = true
    koiMsgSuccess("修改🌻");
    // 重置表单
    resetForm();
    // 标题
    title.value = "用户修改";
    const id = row ? row.id : ids.value[0];
    if (id == null || id == "") {
        koiMsgError("请选择需要修改的数据🌻");
    }
    // 回显数据
    handleEcho(id);
};

// 添加 OR 修改抽屉Ref
const koiDrawerRef = ref();
// 标题
const title = ref("用户类型管理");
// form表单Ref
const formRef = ref<any>();
interface UserForm {
    id?: string;
    username?: string;
    nickname?: string;
    status?: number | string;
    avatar?: string;
    email?: string;
    password?:string
}

// form表单
let form = ref<UserForm>({

});

/** 清空表单数据 */
const resetForm = () => {
    // 等待 DOM 更新完成
    nextTick(() => {
        if (formRef.value) {
            // 重置该表单项，将其值重置为初始值，并移除校验结果
            formRef.value.resetFields();
        }
    });
    form.value = {
        username: "",
        nickname:"",
        status: "",
        avatar: "",
        email: ""
    };
};
// @ts-ignore
const pwdVali = (rule: any, value: any, callback: any) => {
    if (!value) {
        return callback(); // 允许空值直接通过
    }
    if (value.length === 0) {
        return callback();
    } else if (value.length < 6) {
        return callback(new Error("若输入密码,则最少为六位"));
    }

    return callback();
};

/** 表单规则 */
const rules = reactive({
    username: [{ required: true, message: "请输入用户名字", trigger: "blur" }],
    nickname: [{ required: true, message: "请输入用户名称", trigger: "blur" }],
    email: [{ required: true, message: "请输入用户邮箱", trigger: "blur" }],
    // avatar: [{ required: true, message: "请输入用户头像", trigger: "blur" }],
    password: [{ required: true, validator:pwdVali, trigger: "blur" }]
});

// 确定按钮是否显示Loading
const confirmLoading = ref(false);

/** 确定  */
const handleConfirm = () => {
    if (!formRef.value) return;
    confirmLoading.value = true;
    (formRef.value as any).validate(async (valid: any) => {
        if (valid) {
            if (form.value.id != null && form.value.id != "") {
                try {
                    const subForm = {
                        avatar: form.value.avatar,
                        email: form.value.email,
                        id: form.value.id,
                        nickname: form.value.nickname,
                        status: form.value.status,
                        username: form.value.username
                    }
                    console.log("表单", form.value);
                    await changeUserInfo(subForm);
                    koiNoticeSuccess("修改成功🌻");
                    confirmLoading.value = false;
                    koiDrawerRef.value.koiQuickClose();
                    resetForm();
                    handleListPage();
                } catch (error) {
                    console.log(error);
                    confirmLoading.value = false;
                    koiNoticeError("修改失败，请刷新重试🌻");
                }
            } else {
                try {
                    const subForm = {
                        avatar: form.value.avatar,
                        email: form.value.email,
                        nickname: form.value.nickname,
                        password: form.value.password?form.value.password:"",
                        username: form.value.username
                    }
                    await addUserInfo(subForm);
                    koiNoticeSuccess("添加成功🌻");
                    confirmLoading.value = false;
                    koiDrawerRef.value.koiQuickClose();
                    resetForm();
                    handleListPage();
                } catch (error) {
                    console.log(error);
                    confirmLoading.value = false;
                    koiNoticeError("添加失败，请刷新重试🌻");
                }
            }
        } else {
            koiMsgError("验证失败，请检查填写内容🌻");
            confirmLoading.value = false;
        }
    });
};
const closeMethod = () => { 
    needPwd.value = false
    needStatus.value = false
}
/** 取消 */
const handleCancel = () => {
    koiDrawerRef.value.koiClose();
    
};

/** 状态开关 */
const handleSwitch = (row: any) => {
    let text = row.status === 0 ? "启用" : "停用";
    const newStatus = row.status === 1 ? 0 : 1;
    koiMsgBox("确认要[" + text + "]-[" + row.username + "]吗？")
        .then(async () => {
            try {
                await changeStatus({ id: row.id, status: newStatus });
                row.status = newStatus
                koiNoticeSuccess("修改成功🌻");
            } catch (error) {
                koiNoticeError("修改失败，请刷新重试🌻");
            }
        })
        .catch(() => {
            koiMsgError("已取消🌻");
        });
};

/** 删除 */
const handleDelete = (row: any) => {
    const id = row.id;
    if (id == null || id == "") {
        koiMsgWarning("请选择需要删除的数据🌻");
        return;
    }
    koiMsgBox("您确认需要删除用户名称[" + row.username + "]么？")
        .then(async () => {
            try {
                await deleteUser([id]);
                handleListPage()
                koiNoticeSuccess("删除成功🌻");
            } catch (error) {
                console.log(error);
                koiNoticeError("删除失败，请刷新重试🌻");
            }
        })
        .catch(() => {
            koiMsgError("已取消🌻");
        });
};

/** 批量删除 */
const handleBatchDelete = () => {
    if (ids.value.length == 0) {
        koiMsgInfo("请选择需要删除的数据🌻");
        return;
    }
    koiMsgBox("您确认需要进行批量删除么？")
        .then(async () => {
            try {
                console.log("ids", ids.value);
                await deleteUser(ids.value);
                handleListPage()
                koiNoticeSuccess("批量删除成功🌻");
            } catch (error) {
                console.log(error);
                koiNoticeError("批量删除失败，请刷新重试🌻");
            }
        })
        .catch(() => {
            koiMsgError("已取消🌻");
        });
};
</script>

<style lang="scss" scoped>
// 穿梭框高度调整
:deep(.el-transfer-panel__body) {
    height: 400px;
}
</style>
